package com.demo.chapter11future.async;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import static com.demo.chapter11future.Util.*;

public class AsyncShop {

	private final String name;
    private final Random random;

    public AsyncShop(String name) {
        this.name = name;
        random = new Random(name.charAt(0) * name.charAt(1) * name.charAt(2));
    }

    //以异步的方式获取价格和折扣
    public Future<Double> getPrice(String product) {
    	//创建CompletableFuture对象，它会包含计算的结果
        CompletableFuture<Double> futurePrice = new CompletableFuture<>();
        //在另一个线程中以异步的方式执行计算
        new Thread( () -> {
                    try {
                        double price = calculatePrice(product);
                        //需长时间计算的任务并得出结果时，设置Future的返回值
                        futurePrice.complete(price);
                    } catch (Exception ex) {
                    	//通过completeExceptionally抛出异常
                        futurePrice.completeExceptionally(ex);
                    }
        }).start();
        //无需等待还没结束的计算，直接返回Future对象
        return futurePrice;
    }

    private double calculatePrice(String product) {
        delay();
        return format(random.nextDouble() * product.charAt(0) + product.charAt(1));
    }
	
}
